import MarkdownIt from '@lib/markdown-it';
import { message } from 'antd';
import { MessageType } from 'antd/lib/message';
import dynamic from 'next/dynamic';
import * as React from 'react';
import './index.less';

const ReactEditor = dynamic(() => import('./editor'), {
	ssr: false
});

interface EditorProps {
	value: string;
	onChange: (text: string) => void;
}

class Editor extends React.Component<EditorProps> {
	private loading: MessageType | null;
	private upload: (file: File, callback: (url: string) => void) => void;
	constructor(props: any) {
		super(props);
		this.loading = null;
		this.upload = this._upload.bind(this);
	}
	public async _upload(file: File, callback: (url: string) => void) {
		if (this.loading !== null) {
			return;
		}
		if (!/(jpg|jpeg|png|gif|webp)$/i.test(file.name)) {
			message.error('请上传jpg、png、gif、webp格式的图片');
			return;
		}
		if (file.size > 2 * 1024 * 1024) {
			message.error('请上传2MB内的图片');
			return;
		}
		this.loading = message.loading("上传中，请稍候");
		this.setState({
			loading: true
		});
		const formData = new FormData();
		formData.append("smfile", file);
		try {
			const result = await fetch("https://sm.ms/api/upload", {
				method: "POST",
				body: formData
			});
			const res = await result.json();
			if (this.loading) {
				this.loading();
				this.loading = null;
			}
			if (res.code === "success") {
				message.success("上传成功");
				callback(res.data.url);
			} else {
				message.error("上传失败，" + res.msg);
			}
		} catch (e) {
			if (this.loading) {
				this.loading();
				this.loading = null;
			}
			message.error("上传失败，请重试");
		}
	}
	render() {
		return (
			<ReactEditor
				value={this.props.value}
				onChange={(data: any) => this.props.onChange(data.text)}
				renderHTML={(text) => MarkdownIt.render(text)}
				onImageUpload={this.upload}
			></ReactEditor>
		);
	}
}

export default Editor;